'use strict';
const Promise = require('bluebird');

const findOrCreate = require('../lib/mongoose/plugin_findorcreate');

module.exports = mongoose => {
  const SpaceSchema = new mongoose.Schema({
    uid: { type: String, unique: true }, //
    name: { type: String },
    alias: { type: String },
    type: { type: Number, ref: 'type' },
    categories: { type: Array },
    config: { type: Object },
    keywords: { type: String },
    description: { type: String },
  });

  SpaceSchema.plugin(findOrCreate);

  SpaceSchema.statics.getOne = function(query, next) {

    const fn = cb => {
      if (typeof query === 'string') {
        query = {
          uid: query,
        };
      }

      if (typeof query === 'object') {
        if (query._id) {
          return cb(query);
        }

        if (query.uid) {
          return this.findOne({
            uid: query.uid,
          }, function(err, result) {
            if (err) { return cb(err); }
            cb(null, result);
          });
        }
      }

      return cb(new Error('fail to get model with invalid input!'));
    };

    if (next) { return fn(next); }

    const promise = new Promise((resolve, reject) => {
      fn((err, result) => {
        if (err) { return reject(err); }
        resolve(result);
      });
    });

    promise.exec = fn;
    return promise;

  };

  return mongoose.model('Space', SpaceSchema);
};
